package com.abhishekduhoon.tfis;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.abhishekduhoon.tfis.Methods;

public class PFMScan extends HttpServlet {
    
  	private static final long serialVersionUID = 1L;
  	
	protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
        
		String userSequence = request.getParameter("userSequence");
		String transcriptionFactorPFM = request.getParameter("transcriptionFactorPFM");
		String error = "error.jsp";
    	
    	if(userSequence.isEmpty() || transcriptionFactorPFM.isEmpty()){
    		response.sendRedirect(error);
    	}
    	
    	else{
    		
		userSequence = Methods.reformSequence(userSequence);
		String [] transcriptionFactorBindingSequences = Methods.multipleSequences(transcriptionFactorPFM);
		int totalSequences = transcriptionFactorBindingSequences.length;
		for(int i = 1; i < totalSequences; i++){
			transcriptionFactorBindingSequences[i] = Methods.reformSequence(transcriptionFactorBindingSequences[i]);
		}
		
		int transcriptionFactorLength = transcriptionFactorBindingSequences[1].length();
		double [] [] positionFrequencyMatrix = new double [4] [transcriptionFactorLength];
		for(int i = 0; i < 4; i++){
			for(int j = 0; j < transcriptionFactorLength; j++){
				positionFrequencyMatrix[i][j] = 0;
			}
		}
		for(int i = 1; i < totalSequences; i++){
			String transcriptionFactorBindingSequence = transcriptionFactorBindingSequences[i];
			for(int j = 0; j < transcriptionFactorLength; j++){
				char base = transcriptionFactorBindingSequence.charAt(j);
				if(base == 'A'){
                  positionFrequencyMatrix[0][j]++;
				} else if(base == 'C'){
                  positionFrequencyMatrix[1][j]++;
				} else if(base == 'G'){
                  positionFrequencyMatrix[2][j]++;
				} else{
					positionFrequencyMatrix[3][j]++;
				}
			}
		}
        
        String userSequenceCopy = userSequence;
        String colorCodeStart = "<font color='red'>";
        String colorCodeEnd = "</font>";
        double[][] positionWeightMatrix;
    	int userSequenceLength = userSequence.length();
    	String percent = request.getParameter("percent");
        int percentScore = Integer.parseInt(percent);
        double threshold;
    	int totalDetection = 0;
    	int index;
        int indexCopy;
        double score;
        int position;
        char base;

        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {
        	
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<meta charset='UTF-8'>");
            out.println("<title>TFIS v1.0</title>");
            out.println("<meta name='description' content='Transcription Factor Information System'>");
            out.println("<meta name='keywords' content='TFIS, TF, TFBS'>");
            out.println("<link href='css/style.css' rel='stylesheet' type='text/css'>");
            out.println("</head>");
            out.println("<body>");
            out.println("<div id='wrapper'>");
            out.println("<div id='header'>");
            out.println("<div class='top_banner'>");
            out.println("<h1>TFIS v1.0</h1>");
            out.println("<p>Transcription Factor Information System</p>");
            out.println("</div>");
            out.println("</div>");
            out.println("<div id='page_content'>");
            out.println("<div class='navigation'>");
            out.println("<ul>");
            out.println("<li><a href='index.jsp'>Home</a></li>");
            out.println("<li><a href='about.jsp'>About</a></li>");
            out.println("<li><a href='doc.jsp'>Documentation</a></li>");
            out.println("<li><a href='feedback.jsp'>Feedback</a></li>");
            out.println("<li><a href='support.jsp'>Support</a></li>");
            out.println("</ul>");
            out.println("</div>");
            out.println("<div class='main_section'>");
            out.println("<h2>TFIS v1.0 : Result</h2>");
            out.println("<hr>");
            out.println("<div class='common_content'>");
            out.println("<h2>Sequence Length : " + userSequenceLength + "</h2>");
            out.println("<h2>Transcription Factor (TF) Length : " + transcriptionFactorLength + "</h2>");
            out.println("<h2>Total Transcription Factor Binding Sequences Entered : " + --totalSequences + "</h2>");
            out.println("<hr>");
            out.println("<h2>Positions Of Detected Transcription Factor Binding Sites (TFBSs) Are : ");
  
            positionWeightMatrix = Methods.pfmConversion(positionFrequencyMatrix, transcriptionFactorLength);
            threshold = Methods.thresholdCalculator(positionWeightMatrix, transcriptionFactorLength, percentScore);
            for(int i = 0; i <= userSequenceLength - transcriptionFactorLength; i++){
                score = 0;
                position = 0;
                for(int j = i; j < i + transcriptionFactorLength; j++){
                    base = userSequence.charAt(j);
                    if(base == 'A'){
                        score = score + positionWeightMatrix[0][position];
                    }
                    else{
                        if(base == 'C'){
                            score = score + positionWeightMatrix[1][position];
                        }
                        else{
                            if(base == 'G'){
                                score = score + positionWeightMatrix[2][position];
                            }
                            else{
                                score = score + positionWeightMatrix[3][position];
                            }
                        }
                    }
                    position++;
                }
                if(score >= threshold){
                    index = i;
                    indexCopy = index + totalDetection * 25;
                    userSequenceCopy = Methods.insertCode(userSequenceCopy, colorCodeStart, indexCopy);
                    indexCopy = indexCopy + transcriptionFactorLength + 18;
                    userSequenceCopy = Methods.insertCode(userSequenceCopy, colorCodeEnd, indexCopy);
                    index++;
                    totalDetection++;
                    out.println("<h2>" + totalDetection + " -> " + index + "</h2>");
                    i = i + transcriptionFactorLength - 1;
                }
            
            }
      
            out.println("<h2>Total Transcription Factor Binding Sites (TFBSs) Detected : " + totalDetection + "</h2>");
            out.println("<hr>");
            out.println("<h2>FASTA Format :</h2>");
            out.println("<span><h3>"+userSequenceCopy+"</h3></span>");
            out.println("</div>");
            out.println("</div>");
            out.println("<div id='footer'>Sengupta <i>et al.</i> | Developed and Maintained by <a href='http://www.abhishekduhoon.com' target='_blank'>Abhishek Kumar</a>.");
            out.println("</div>");
            out.println("</div>");
            out.println("</body>");
            out.println("</html>");
        }
    	}
    }
}                               
       
